package de.velvettear.squirrel.gui;

import android.app.Activity;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import de.velvettear.squirrel.executors.SecurityCamExecutor;
import de.velvettear.squirrel.util.CameraHelper;

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {

	private static Activity activity;
	private static Camera mCamera;	
    private SurfaceHolder mHolder;
         
    public CameraPreview(Context context, Activity activity) {
        super(context);
        this.activity = activity;
        mHolder = getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);        
    }

    public void surfaceCreated(SurfaceHolder holder) {
    	try {
    		mCamera = CameraHelper.getBackCamera();
			mCamera.setPreviewDisplay(holder);
		} catch (Exception e) {
			if (e.getMessage() != null) {
				Log.e("surfaceCreated()", e.getMessage());
			}
		}
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        mCamera.stopPreview();
        mCamera = null;
        SecurityCamExecutor.stopTakingPictures();
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    	if (mCamera == null) {
    		mCamera = CameraHelper.getBackCamera();
    	}
        Camera.Parameters parameters = mCamera.getParameters();
        parameters.setPreviewSize(w, h);
        mCamera.setParameters(parameters);
        setCameraDisplayOrientation();
        mCamera.startPreview();
    }

    public static void setCameraDisplayOrientation() {
        CameraInfo info = new CameraInfo();
        Camera.getCameraInfo(CameraHelper.getBackCameraID(), info);
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0: degrees = 0; break;
            case Surface.ROTATION_90: degrees = 90; break;
            case Surface.ROTATION_180: degrees = 180; break;
            case Surface.ROTATION_270: degrees = 270; break;
        }

        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;
        } else {
            result = (info.orientation - degrees + 360) % 360;
        }
        
        mCamera.setDisplayOrientation(result);
    }
    
}
